package com.lanou3g.ssm.web;

import com.lanou3g.ssm.bean.User;
import com.lanou3g.ssm.service.UserService;
import com.lanou3g.ssm.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.jws.WebParam;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * 处理用户相关请求
 */
@Slf4j
@Controller
// 类上的RequestMapping会应用该Controller所有方法上，给方法访问路径加一个前缀
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 登录
     * @param user
     * @param session
     * @param model
     * @return
     */
    @RequestMapping("/login")
    public String login(User user, HttpSession session, Model model) {
        if(StringUtil.isBlank(user.getUsername()) || StringUtil.isBlank(user.getPassword())) {
            model.addAttribute("errorMsg", "登录错误，请输入用户名，密码！");
            return "login";
        }
        String userName = user.getUsername();
        String password = user.getPassword();

        User userInfo = userService.findUserByUsername(userName);
        if(userInfo == null) {
            model.addAttribute("errorMsg", "用户不存在，请先注册！");
            return "login";
        }
        if(!userInfo.getPassword().equals(password)) {
            model.addAttribute("errorMsg", "用户名或密码不正确！");
            return "login";
        }
        // 将登录后的用户信息放在session中
        session.setAttribute("userInfo", userInfo);

        // 转发到MessageController的to_main方法
        return "main";
    }

    /**
     * 用户注册
     * @param user
     * @return
     */
    @PostMapping("/register")
    public String register(User user, HttpSession session) {
        userService.registerUser(user, session);
        return "main";
    }

    // 退出登录
    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "login";
    }


    /**
     * 显示用户资料
     * @param session
     * @return
     */
    @RequestMapping("/show_user")
    public String showUser(HttpSession session) {
        return "user/show_user";
    }

    /**
     * 更新用户资料
     * @param user
     * @param session
     * @return
     */
    @RequestMapping("/update")
    public String updateUser(User user, HttpSession session) {
        userService.updateUser(user, session);
        return "user/show_user";
    }
}
